import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class StorageUtil {
  StorageUtil._();

  static late SharedPreferences _instance;

  static Future<void> init() async => _instance = await SharedPreferences.getInstance();

  static T? get<T>(String key) {
    if (T is bool) {
      return _instance.getBool(key) as T;
    } else if (T is double) {
      return _instance.getDouble(key) as T;
    } else if (T is int) {
      return _instance.getInt(key) as T;
    } else if (T is String) {
      return _instance.getString(key) as T;
    } else {
      String? value = _instance.getString(key);
      return value == null ? null : jsonDecode(value);
    }
  }

  static void set<T>(String key, T value) {
    if (T is bool) {
      _instance.setBool(key, value as bool);
    } else if (T is double) {
      _instance.setDouble(key, value as double);
    } else if (T is int) {
      _instance.setInt(key, value as int);
    } else if (T is String) {
      _instance.setString(key, value as String);
    } else {
      _instance.setString(key, jsonEncode(value));
    }
  }

  static Future<bool> del(String key) async => has(key) && await _instance.remove(key);

  static bool has(String key) => _instance.containsKey(key);

  static void cls() async => _instance.clear();
}
